<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selecteddeparts" label="适用门店">
          <a-cascader
            :options="departModel.departTreeOptions"
            @change="onDepartChange"
            :showSearch="true"
            expand-trigger="hover"
            placeholder=""
            :fieldNames="departModel.fieldNames"
            style="width: 300px"
            v-model="model.selecteddeparts"
          />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ruleType" label="限制方式">
          <a-radio-group name="ruleType" v-model="model.ruleType" @change="handleChange">
            <a-radio :value="1" :style="radioStyle">
              限制优惠金额0-
              <a-input-number v-model="model.ruleVal" :min="1" :max="99" :step="1" :disabled="disabled.rule1" :formatter="limitNumber"
                    :parser="limitNumber"/> 元
            </a-radio>
            <a-radio :value="2" :style="radioStyle">
              限制优惠金额不能超过商品的销售价
              <a-input-number v-model="model.ruleVal2" :min="1" :max="99" :step="1" :disabled="disabled.rule2" :formatter="limitNumber"
                    :parser="limitNumber"/> %
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="提示">
          <span>计算时舍去小数位取整</span>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import { queryDepartTreeList1 } from '@/api/api'
import { limitNumber } from '@/utils/util'

export default {
  name: 'PosOrderAdjustRuleModal',
  data() {
    return {
      title: '操作',
      visible: false,
      limitNumber,
      model: {},
      departModel: {
        departTreeOptions: [],
        orgIds: '',
        orgNames: '',
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      disabled: {
        rule1: false,
        rule2: false,
      },
      radioStyle: {
        display: 'block',
        height: '40px',
        lineHeight: '40px',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      validatorRules: {
        selecteddeparts: [{ required: true, message: '必填项' }],
        ruleType: [{ required: true, message: '必填项' }],
        ruleVal: [{ required: true, message: '必填项' }],
      },
      url: {
        add: '/cashier/posOrderAdjustRule/add',
        edit: '/cashier/posOrderAdjustRule/edit',
      },
    }
  },
  created() {
    this.loadDepartTree()
  },
  methods: {
    handleChange(e) {
      let checked = e.target.value
      console.log('checked', checked)
      if (this.model.ruleType == 1) {
        this.disabled.rule1 = false
        this.disabled.rule2 = true
        this.model.ruleVal2 = ''
      } else {
        this.disabled.rule2 = false
        this.disabled.rule1 = true
        this.model.ruleVal = ''
      }
    },
    loadDepartTree() {
      queryDepartTreeList1({ orgTypes: '2' }).then((res) => {
        if (res.success) {
          this.departModel.departTreeOptions = res.result
          this.departModel.departTreeOptions.forEach((x) => {
            x['children'] = [{ title: '全部门店', value: '0' }]
          })
        }
      })
    },
    onDepartChange(value, selectedOptions) {
      console.log('value:', value)
      console.log('selectedOptions:', selectedOptions)
      this.departModel.orgIds = value && value.length > 0 ? value[0] : ''
      this.departModel.orgNames = selectedOptions && selectedOptions.length > 0 ? selectedOptions[0].departName : ''
    },
    add() {
      //初始化默认值
      this.edit({})
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      if (this.model.id) {
        this.model.selecteddeparts = [this.model.orgId, '0']
        this.departModel.orgIds = this.model.orgId
        this.departModel.orgNames = this.model.orgName
        if (this.model.ruleType == 2) {
          this.$set(this.model, 'ruleVal2', this.model.ruleVal)
          this.model.ruleVal = ''
          this.disabled.rule1 = true
        } else {
          this.disabled.rule2 = true
          this.$set(this.model, 'ruleVal', parseFloat(this.model.ruleVal)/100)
        }
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.$refs.form.clearValidate()
    },
    buildParam() {
      let ruleVal = this.model.ruleType == 1 ? parseFloat(this.model.ruleVal) * 100 : parseFloat(this.model.ruleVal2)
      return {
        id: this.model.id,
        orgId: this.departModel.orgIds,
        orgName: this.departModel.orgNames,
        ruleType: this.model.ruleType,
        ruleVal: ruleVal,
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let param = this.buildParam()
          console.log('param', param)
          httpAction(httpurl, param, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
  },
}
</script>

<style lang="less" scoped>
</style>